<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="zh-CN">

<head>
<title>js第4课-03-获取一组元素-03-全选/不选/反选</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="description" content="这是js第4课-03-获取一组元素-03-全选/不选/反选">
<br>
<br>js第4课-03-获取一组元素-03-全选/不选/反选
<br>

<style type="text/css">
</style>

<script type="text/javascript">
	window.onload = function() {
		var oBtnAllSelect = document.getElementById("btnAllSelect");
		var oBtnNoSelect = document.getElementById("btnNoSelect");
		var oBtnInverseSelect = document.getElementById("btnInverseSelect");
		var oDiv = document.getElementById("divCheckbox");
		//var oCh = document.getElementsByTagName("input");
		// 从oDiv元素里选取input元素
		var oCh = oDiv.getElementsByTagName("input");

		// 全选
		oBtnAllSelect.onclick = function() {
			// oCh[0].checked = true;
			for ( var k = 0; k < oCh.length; k++) {
				oCh[k].checked = true;
			}
		};

		// 不选
		oBtnNoSelect.onclick = function() {
			for ( var k = 0; k < oCh.length; k++) {
				oCh[k].checked = false;
			}
		};

		// 反选
		oBtnInverseSelect.onclick = function() {
			for ( var k = 0; k < oCh.length; k++) {
				// 注意if条件里用双等号
				if (oCh[k].checked == true) {
					oCh[k].checked = false;
				} else {
					oCh[k].checked = true;
				}
			}
		};

	}
</script>

</head>

<body>
	<!-- 
		给button和checkbox加div的目的是为了防止下边的代码把button也取到：
		var oCh = document.getElementsByTagName("input"); 
	-->
	<div id="divButton">
		<input id="btnAllSelect" type="button" value="全选" /> <br> <input
			id="btnNoSelect" type="button" value="不选" /> <br> <input
			id="btnInverseSelect" type="button" value="反选" /> <br>
	</div>
	<div id="divCheckbox">
		<input type="checkbox" /> <br> <input type="checkbox" /> <br>
		<input type="checkbox" /> <br> <input type="checkbox" /> <br>
		<input type="checkbox" /> <br> <input type="checkbox" /> <br>
		<input type="checkbox" /> <br>
	</div>
</body>

</html>